<template>
  <!-- 反馈 -->
  <view class="evaluate container">
    <u--form
      labelPosition="left"
      :model="feedbackInfo"
      :rules="rules"
      ref="evaluateForm"
    >
      <u-form-item
        prop="score"
        label="评分"
        labelPosition="top"
        labelWidth="200rpx"
      >
        <u-rate
          :count="count"
          allowHalf
          inactive-color="#2979ff"
          v-model="feedbackInfo.score"
        >
        </u-rate>
      </u-form-item>

      <u-form-item
        prop="server_content"
        label="综合评价"
        labelPosition="top"
        labelWidth="200rpx"
      >
        <u--textarea
          v-model="feedbackInfo.server_content"
          count
          height="100"
          :maxlength="500"
          placeholder="请输入内容"
        ></u--textarea>
      </u-form-item>

      <u-form-item label="是否匿名" labelWidth="200rpx">
        <template slot="right">
          <u-switch
            v-model="feedbackInfo.isAnonymous"
            size="20"
            @change="change"
          ></u-switch>
        </template>
      </u-form-item>
    </u--form>

    <button class="circle-button btn-active" style="width: 90%" @click="submit">
      提交
    </button>
  </view>
</template>

<script>
import config from "@/common/config";
import userInfoMixin from "@/common/mixins/info";
import { getModelInfo, createModel, updateModel } from "@/api";
export default {
  mixins: [userInfoMixin],
  data() {
    return {
      feedbackInfo: {
        score: 0,
        server_content: "",
        isAnonymous: true, //是否匿名
      }, // 反馈信息
      rules: {
        server_content: {
          type: "string",
          required: true,
          message: "请输入反馈内容",
          trigger: ["blur", "change"],
        },
        score: {
          type: "number",
          required: true,
          message: "请输入评分",
          trigger: ["change"],
        },
      },
      show: false,
      content:
        "感谢你对我们的关注与支持，我们会认真处理你的反馈，尽快完善相关功能",
      fileList1: [],
      count: 5,
      orderData: {},
      reqUserInfo: {},
    };
  },
  methods: {
    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1);
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file);
      let fileListLen = this[`fileList${event.name}`].length;
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url);
        let item = this[`fileList${event.name}`][fileListLen];
        this[`fileList${event.name}`].splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "",
            url: result,
          })
        );
        fileListLen++;
      }
    },
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: config.baseURL,
          header: {
            Authorization: `${that.$storage.get(`${config.storage}Token`)}`,
          }, // 仅为示例，非真实的接口地址
          filePath: url,
          name: "file",
          formData: {
            user: "test",
          },
          success: (res) => {
            setTimeout(() => {
              resolve(res.data.data);
            }, 1000);
          },
        });
      });
    },
    change(value) {
      this.feedbackInfo.isAnonymous = value;
    },
    // 创建评价
    async createEvaluate() {
      let { realName, id, headIcon = "" } = this.userInfo;
      let { baseInfo_id, current_project_Info } = this.orderData;

      this.reqUserInfo = {
        evaluate_name: realName,
        evaluate_avatar: [
          {
            url: headIcon,
            name: this.userInfo.headIcon.split
              ? this.userInfo.headIcon.split("/").pop()
              : "",
            fileId: Date.now(),
          },
        ],
        project_id: current_project_Info,
        server_id: baseInfo_id,
      };
      let reqData = {
        ...this.feedbackInfo,
        ...this.reqUserInfo,
      };
      const { data } = await createModel("65b856b55efd5153ff55cd80", reqData);
      if (data) {
        uni.$u.toast("评价成功");
        this.$helper.rollback(1200);
      }
    },
    // 修改订单状态
    async updateOrderStatus() {
      await updateModel(
        "66002f4f5efd5153ff566ec3",
        {
          ...this.orderData,
          status_code: 6,
        },
        this.orderData._id
      );
    },
    // 提交
    submit() {
      this.$refs.evaluateForm
        .validate()
        .then(async (res) => {
          await Promise.all([this.createEvaluate(), this.updateOrderStatus()]);
          uni.$u.toast("提交成功");
          this.$helper.rollback(1000);
        })
        .catch((errors) => {
          uni.$u.toast("校验失败");
        });
    },
  },
  async onLoad(options) {
    const { data } = await getModelInfo(
      "66002f4f5efd5153ff566ec3",
      options.orderId
    );
    this.orderData = data;
  },
  onReady() {
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    this.$refs.evaluateForm.setRules(this.rules);
  },
};
</script>

<style lang="scss" scoped>
.evaluate {
  position: relative;

  button {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    bottom: constant(safe-area-inset-bottom) !important;
    bottom: env(safe-area-inset-bottom) !important;
  }

  &-warp {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
  }
}
::v-deep .u-upload__wrap {
  justify-content: center;
  align-items: center;
}

::v-deep .u-upload__wrap > .u-upload__button {
  background-color: #fff;
  border-radius: 16rpx;
  margin: 0;
}

::v-deep .u-textarea {
  margin: 0 20rpx;
  box-shadow: 0px 3px 12px 1px rgba(178, 178, 178, 0.16);
  border-radius: 10rpx;
}

::v-deep .u-form-item__body__left__content {
  margin: 0 24rpx;
}

::v-deep .u-rate__content {
  padding: 20rpx;
}

::v-deep .u-switch {
  margin-right: 20rpx;
}
</style>
